/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.cid.jsfproducts.controllerbeans;

import edu.chl.cid.jsfproducts.NonexistentEntityException;
import edu.chl.cid.jsfproducts.Product;
import edu.chl.cid.jsfproducts.ProductJpaCtrl;
import edu.chl.cid.jsfproducts.modelbeans.ShoppingCartModelBean;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Mikey
 */
@ManagedBean
@ViewScoped
public class ViewProductsControllerBean {
    
    @EJB
    private ProductJpaCtrl productJpaCtrl;
    @ManagedProperty("#{shoppingCartModelBean}")
    private ShoppingCartModelBean cart;
    

    /** Creates a new instance of ViewProductsControllerBean */
    public ViewProductsControllerBean() {
    }
    
    public List<Product> getProducts(){
        return productJpaCtrl.findEntities();
    }
    
    public ShoppingCartModelBean getCart() {
        return cart;
    }

    public void setCart(ShoppingCartModelBean cart) {
        this.cart = cart;
    }
    
    
    
    public void addToCart(Product p) {
        cart.addProduct(p);
    }
    
    public void removeProduct(Product product) throws NonexistentEntityException {
        cart.removeProducts(product);
        productJpaCtrl.destroy(product.getId());
    }
    
    public String emptyCart(){
        
        ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).invalidate();
        
        return "onViewProducts";
        
    }
}
